package cc.mrbird.febs.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author: Mr.Yang
 * @CreateTime: 2022-08-07
 * @Description:
 */
@Slf4j
public class OrderNoUtil {

    /**
     * 生成订单号（25位）：时间（精确到毫秒）+3位随机数+5位用户id
     */
    public static synchronized String getOrderNum(Long userId) {
        //时间（精确到毫秒）
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String localDate = LocalDateTime.now().format(ofPattern);
        //3位随机数
        String randomNumeric = RandomStringUtils.randomNumeric(3);
        //5位用户id
        int subStrLength = 5;
        String sUserId = userId.toString();
        int length = sUserId.length();
        String str;
        if (length >= subStrLength) {
            str = sUserId.substring(length - subStrLength, length);
        } else {
            str = String.format("%0" + subStrLength + "d", userId);
        }
        String orderNum = localDate + randomNumeric + str;
//        log.info("订单号:{}", orderNum);
//        log.info(String.valueOf("20220807195351715918000001".length()));
        return orderNum;
    }

    public static void main(String[] args) {
        String orderNum = getOrderNum(2326L);
        System.out.println(orderNum);
        System.out.println(orderNum.length());
    }


}
